<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Controller;

use App\Constants\ErrorCode;
use App\Service\PhoneService;
use App\Service\UserService;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;

class UserLogin extends AbstractController
{
    /**
     * @Inject
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * @Inject
     * @var PhoneService
     */
    protected $phoneService;

    /**
     * @Inject
     * @var UserService
     */
    protected $userService;

    /**
     * 用户登录.
     */
    public function login()
    {
        $data = $this->request->all();
        $validate = $this->validationFactory->make(
            $data,
            [
                'account' => 'required|mobile',
                'code' => 'required',
            ],
            [
                'account.required' => '手机号码不能为空',
                'account.mobile' => '手机号码不合规',
                'code.required' => '验证码不能为空',
            ]
        );
        if ($validate->fails()) {
            $msg = $validate->errors()->first();
            return $this->success([], ErrorCode::PARAM_ERROR, $msg);
        }
        Db::beginTransaction();
        try {
            $ret = $this->userService->userLogin($data['account'], $data['code']);
            Db::commit();
            return $this->success($ret);
        } catch (\Exception $e) {
            Db::rollBack();
            $code = empty($e->getCode()) ? ErrorCode::SERVER_ERROR : $e->getCode();
            $msg = $e->getMessage();
            return $this->success([], $code, $msg);
        }
    }

    /**
     * 发送手机验证码
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function sendPhoneCode()
    {
        $validate = $this->validationFactory->make(
            $this->request->all(),
            [
                'account' => 'required|mobile',
            ],
            [
                'account.required' => '手机号码不能为空',
                'account.mobile' => '手机号码不合规',
            ]
        );
        if ($validate->fails()) {
            $msg = $validate->errors()->first();
            return $this->success([], ErrorCode::PARAM_ERROR, $msg);
        }
        $account = $this->request->input('account');
        $ret = $this->phoneService->sendAliPhoneCode($account);
        if ($ret) {
            return $this->success();
        }
        return $this->success([], ErrorCode::SERVER_ERROR, '发送短信失败');
    }
}
